<template>
  <van-row>
    <van-col span="24">
      <!-- 列表项 -->
        <van-row style="margin-top: 5px;padding: 10px 0;cursor: pointer;background-color: aliceblue;" 
                v-for="order in orderList" :key="order.orderId"
               >
            <van-col :span="24">
                <van-row  @click="showOrderDetail(order.orderId)">
                    <van-col :span="22" :offset="2" >订单编号:{{order.orderNumber}}</van-col>
                </van-row>
                <van-row>
                    <van-col :span="22" :offset="2">下单时间:{{order.orderDate}}</van-col>
                </van-row>
                <van-row>
                    <van-col :span="22" :offset="2">总金额:{{order.orderTotal}}</van-col>
                </van-row>
                <van-row>
                    <van-col :span="5" :offset="19">
                        <van-button v-show="order.orderState==0" size="small" type="danger" @click="toPayOrder(order)">去支付</van-button>
                        <van-button v-show="order.orderState==1" size="small" type="primary" disabled>已支付</van-button>
                    </van-col>
                </van-row>
            </van-col>
        </van-row>

        <div style="height: 100px;"></div>
    </van-col>
  </van-row>
</template>

<script setup>
import { ref,getCurrentInstance, onMounted } from 'vue';
import { showNotify } from 'vant';
import '@vant/touch-emulator';

const {proxy} = getCurrentInstance();

//订单列表
const orderList = ref([]);

//通过用户id查询该用户所有订单
const getOrderByUserId = ()=>{
    proxy.$axios({
        method: 'get',
        url: '/order/user/'+userId.value
    }).then(res=>{
        let resultBean = res.data;
        if(resultBean.code == 200){
           orderList.value = resultBean.data;
        }else{
            showNotify({message: resultBean.msg});
        }
    }).catch(error=>{
        showNotify({message: error.message});
    })
}

//支付订单的方法   修改支付状态
const toPayOrder = (order)=>{

    let obj = Object.assign({},order);
    obj.orderState = 1;  //设置为已支付状态

    proxy.$axios({
        method: 'put',
        url: '/order/update',
        data: obj
    }).then(res=>{
        let resultBean = res.data;
        if(resultBean.code == 200){
            showNotify({message: '支付成功'});
            order.orderState = 1; //修改显示状态
        }else{
            showNotify({message: resultBean.msg});
        }
    }).catch(error=>{
        showNotify({message: error.message});
    })
}

const showOrderDetail = (orderId)=>{
    proxy.$router.push("/main/orderDetail/"+orderId);
}

//当前正在登录的用户id
const userId = ref(null);

onMounted(()=>{
    let userJson = window.localStorage.getItem("loginUser");
    
    if(!userJson){
      showNotify({message: '请先登录'});
      proxy.$router.push('/login');
      return;
    }

    let user = JSON.parse(userJson);


    //获取用户id
    userId.value = user.userId; //从本地存储获取
    
    getOrderByUserId();
})

</script>

<style>
</style>